package com.LeeCode;

/**
 * 旋转链表
 */

public class Code061 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 2;
        ListNode head = Utils.arrayToListNode(arr);
        Utils.printListNode(new Code061().rotateRight(head, k));
    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) return head;
        ListNode dummy = new ListNode(0, head);
        ListNode slow = dummy, fast = dummy;
        int n = 0;
        for (ListNode cur = head; cur != null; cur = cur.next) {
            n++;
        }
        k = k % n;
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }

        fast.next = dummy.next;
        dummy.next = slow.next;
        slow.next = null;
        return dummy.next;
    }
}
